/*
 * Copyright (c) 2024 Black Sesame Technologies
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <cstdlib>
#include <string>
#include <unistd.h>
#include "dal/config_loader.h"
#include "dal_cyclonedds/utils/log.hpp"
#include "dal_cyclonedds/converter/QosConverter.hpp"
#include "dal_cyclonedds/config_manager/ConfigManager.hpp"

dal_ret_t dal_load_config_from_path(const char* path, void* config)
{
    (void*)config;

    do {
        if (path == nullptr) {
            LOG_INFO() << "[configloader - api mode] path is invalid." << LOG_ENDL;
            break;
        }

        if (access(path, F_OK) != 0) {
            LOG_INFO() << "[configloader - api mode] config file " << path << " not exist."
                       << LOG_ENDL;
            break;
        }

        if (setenv("CYCLONEDDS_URI", path, 1)) {
            LOG_INFO() << "[configloader - api mode] CYCLONEDDS_URI env set fail." << LOG_ENDL;
            break;
        }

        // if go to here, means api path takes effect.
        ConfigManager::GetInstance()->setCycloneddsProfilePath(path);
        ConfigManager::GetInstance()->setConfigType(
            ConfigManager::ConfigType::CONFIG_TYPE_SET_BY_API);
        LOG_INFO() << "[configloader - api mode] success, "
                   << "config file [" << path << "] takes effect." << LOG_ENDL;

        return DAL_RETCODE_OK;
    } while (true);

    ConfigManager::GetInstance()->clearSetting();
    if (ConfigManager::GetInstance()->loadConfigProfileByEnv()) {
        // if go to here, means env path takes effect.
        return DAL_RETCODE_OK;
    }

    return DAL_RETCODE_ERROR;
}